<template>
  <div class="projectCenter">
    <div class="projectCenter_top">
      <div>项目中心</div>
      <div>
        <el-button type="success" @click="exportTable">导入</el-button>
        <!-- <el-button type="warning" @click="exportTableMore">批量导入</el-button> -->
        <el-button type="danger" @click="deleteMore">批量删除</el-button>
        <el-button type="primary" @click="exportProject">导出</el-button>
      </div>
    </div>
    <div>
      <el-table ref="multipleTableRef" :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column fixed type="selection" width="55" />
        <el-table-column label="截止日期" width="240">
          <template #default="scope">{{ dayjs(scope.row.deliveryDate).format('YYYY-MM-DD HH:mm:ss') }}</template>
        </el-table-column>
        <el-table-column property="projectName" label="项目名称" width="240" />
        <el-table-column property="status" label="目前状态" width="240">
          <template #default="scope">
            <el-tag v-if="scope.row.status === '进行中'" type="success">进行中</el-tag>
            <el-tag v-if="scope.row.status === '未开始'" type="warning">未开始</el-tag>
            <el-tag v-if="scope.row.status === '继续跟进'" type="danger">继续跟进</el-tag>
            <el-tag v-if="scope.row.status === '已完成'" type="primary">已完成</el-tag>
          </template>
        </el-table-column>
        <el-table-column property="projectLeader" label="负责人" width="240" />
        <el-table-column property="projectProgress" label="完成进度" show-overflow-tooltip />
        <el-table-column property="address" label="操作" width="240">
          <template #default="scope">
            <el-button size="small" type="success" @click="showProject(scope.$index, scope.row)">详情</el-button>
            <el-button size="small" type="primary" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="showDeleteTip(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="footer_page">
      <el-config-provider>
        <el-pagination v-model:current-page="currentPage1" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40]"
          background layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange"></el-pagination>
      </el-config-provider>
    </div>
    <el-dialog v-model="dialogVisible" title="Tips" width="500">
      <span>确定删除吗？</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleDelete()"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="isExport" title="Tips" width="500">
      <span>确定导出吗？</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="isExport = false">取消</el-button>
          <el-button type="primary" @click="exportSure"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="showDialogOverflowVisible" title="Tips" width="680" draggable overflow>
      <template #header> 项目详情 </template>
      <div>
        <el-form ref="ruleFormRef" style="max-width: 600px" status-icon label-width="auto" class="demo-ruleForm"
          label-position="top">
          <el-row>
            <el-col :span="11">
              <el-form-item label="项目名称:" prop="projectName">
                <el-input v-model="projectDetail.projectName" type="text" autocomplete="off" placeholder="请输入内容"
                  disabled />
              </el-form-item>
            </el-col>
            <el-col :span="2"></el-col>
            <el-col :span="11">
              <el-form-item label="项目进度:" prop="projectProgress">
                <el-input v-model="projectDetail.projectProgress" type="text" autocomplete="off" placeholder="请输入内容"
                  disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="11">
              <el-form-item label="负责人：" prop="projectLeader">
                <el-input v-model.number="projectDetail.projectLeader" placeholder="请输入内容" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="2"></el-col>
            <el-col :span="11">
              <el-form-item label="交付日期：" prop="deliveryDate">
                <el-input v-model.number="projectDetail.deliveryDate" placeholder="请输入内容" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="11">
              <el-form-item label="状态：" prop="status">
                <el-input v-model.number="projectDetail.status" placeholder="请输入内容" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="2"></el-col>
            <el-col :span="11">
              <el-form-item label="项目人员：" prop="selectedLeaders">
                <el-input v-model.number="projectDetail.selectedLeaders" placeholder="请输入内容" disabled />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showDialogOverflowVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="editDialogOverflowVisible" title="Tips" width="680" draggable overflow>
      <template #header> 项目详情 </template>
      {{ projectDetail.projectLeaderId }}
      {{ projectDetail.projectLeader }}
      <div>
        <el-form ref="ruleFormRef" style="max-width: 600px" status-icon label-width="auto" class="demo-ruleForm"
          label-position="top">
          <el-row>
            <el-col :span="11">
              <el-form-item label="项目名称:" prop="projectName">
                <el-input v-model="projectDetail.projectName" type="text" autocomplete="off" placeholder="请输入内容" />
              </el-form-item>
            </el-col>
            <el-col :span="2"></el-col>
            <el-col :span="11">
              <el-form-item label="项目进度:" prop="projectProgress">
                <el-input v-model="projectDetail.projectProgress" type="text" autocomplete="off" placeholder="请输入内容" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="11">
              <el-form-item label="负责人：" prop="projectLeader">
                <el-select collapse-tags v-model="projectDetail.projectLeaderId" multiple placeholder="Select"
                  @change="handleCheckChange" style="width: 240px">
                  <el-option v-for="item in allUserInfo" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
                <!-- <el-input v-model.number="projectDetail.projectLeader" placeholder="请输入内容" /> -->
              </el-form-item>
            </el-col>
            <el-col :span="2"></el-col>
            <el-col :span="11">
              <el-form-item label="交付日期：" prop="deliveryDate">
                <el-date-picker v-model="projectDetail.deliveryDate" type="date" placeholder="请输入内容" />
                <!-- <el-input v-model.number="projectDetail.deliveryDate" placeholder="请输入内容" /> -->
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="11">
              <el-form-item label="状态：" prop="status">
                <el-select v-model="projectDetail.status" placeholder="请选择">
                  <el-option v-for="item in statusArr" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
                <!-- <el-input v-model.number="projectDetail.status" placeholder="请输入内容" /> -->
              </el-form-item>
            </el-col>
            <el-col :span="2"></el-col>
            <el-col :span="11">
              <el-form-item label="项目人员：" prop="selectedLeaders">
                <el-select collapse-tags v-model="projectDetail.selectedLeaders" multiple placeholder="Select"
                  style="width: 240px">
                  <el-option v-for="item in allUserInfo" :key="item.id" :label="item.id" :value="item.name" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogOverflowVisible = false">关闭</el-button>
          <el-button @click="editProject">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="uploadFileDialog" title="Tips" width="680" draggable overflow>
      <template #header> 项目详情 </template>
      <div>
        <el-upload ref="upload" class="upload-demo" drag accept=".xls,.xlsx" :on-error="uploaFileError" :limit="1"
          :auto-upload="false" @submit="uploaFileMethod" :on-change="handleChange">
          <template #trigger>
            <el-button type="primary">上传文件</el-button>
          </template>

        </el-upload>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="uploadFileDialog = false">关闭</el-button>
          <el-button @click="uploaFileSure">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, watchEffect, reactive } from "vue";
import webRequest from "../utils/request";
import { ElMessage } from "element-plus";
import FileSaver from 'file-saver';
import dayjs from 'dayjs';
export default {
  setup() {
    let tableData = ref([]);
    const currentPage1 = ref(1);
    const total = ref(0);
    const choseId = ref(0);
    const dialogVisible = ref(false);
    const showDialogOverflowVisible = ref(false);
    const editDialogOverflowVisible = ref(false);
    const uploadFileDialog = ref(false);
    const upload = ref(null);
    const isExport = ref(false);
    // 存储上传文件
    let file = ref(null);
    let filePath = ref(null);
    let pageSize = 10;
    const projectDetail = ref({
      name: "",
      sex: "",
      birth: "",
      phone: "",
      political: "",
      education: "",
      department: "",
      position: "",
      entryTime: "",
      status: "",
    });
    const allUserInfo = ref([]);
    const statusArr = [
      {
        value: "进行中",
        label: "进行中",
      },
      {
        value: "已完成",
        label: "已完成",
      },
      {
        value: "已暂停",
        label: "已暂停",
      },
    ];
    // 分页获取项目数据
    const getProjectByPageData = async (val) => {
      const res = await webRequest.projectDetail.getProjectByPageMethod({
        currentPage: currentPage1.value,
        pageSize: val || pageSize,
      });
      console.log(res.data.data.rows, "res");
      tableData.value = res.data.data.rows;
      total.value = res.data.data.count;
      projectDetail.value = res.data.data.rows;
      projectDetail.value.projectLeaderId = res.data.data.rows.map(item => item.projectLeaderId);
      console.log(total, "totaltotaltotal", res.data,tableData);
    };
    let names = reactive([]);
    const handleCheckChange = (checkedKeys, info) => {
      names = []
      allUserInfo.value.filter(item => {
        if (checkedKeys.includes(item.id)) {
          names.push(item.name)
        }
      })
      projectDetail.projectLeaderId = checkedKeys
      console.log(checkedKeys, info, names);
    };
    // 删除项目
    const handleDelete = async () => {
      const res = await webRequest.projectDetail.deleteProjectMethod({
        id: choseId.value,
      });
      console.log(res);
      getProjectByPageData();
      dialogVisible.value = false;
      ElMessage({
        message: "删除成功",
        grouping: true,
        type: "success",
      });
    };
    //  删除项目提示
    const showDeleteTip = (index, row) => {
      dialogVisible.value = true;
      choseId.value = row.id;
      console.log(index, row);
    };
    // 使用 watchEffect 监听 currentPage1 的变化，以重新获取数据
    watchEffect(() => {
      getProjectByPageData();
    });
    //  分页大小改变
    const handleSizeChange = (val) => {
      console.log(`${val} items per page`);
      getProjectByPageData(val);
    };
    // 分页切换
    const handleCurrentChange = (val) => {
      console.log(`current page: ${val}`);
      currentPage1.value = val;
    };
    // 展示项目详情
    const showProject = (index, item) => {
      console.log(showDialogOverflowVisible, projectDetail, 'dsjkfghsdkjfh');
      projectDetail.value = item;
      showDialogOverflowVisible.value = true;
    };
    // 编辑项目弹框
    const handleEdit = (index, item) => {
      console.log(index,item, 'fdlkhdfjklshgljkdsh');
      projectDetail.value = item;
      projectDetail.value.projectLeader = item.projectLeader.split(',');
      editDialogOverflowVisible.value = true;
    };
    // 编辑项目请求
    const editProject = async () => {
      console.log(names, 'names');
      const res = await webRequest.projectDetail.editProjectMethod({
        id: projectDetail.value.id,
        projectName: projectDetail.value.projectName,
        projectProgress: projectDetail.value.projectProgress,
        projectLeader: names,
        deliveryDate: projectDetail.value.deliveryDate,
        status: projectDetail.value.status,
        selectedLeaders: projectDetail.value.selectedLeaders,
        projectLeaderId: projectDetail.value.projectLeaderId,
      });
      console.log(res);
      getProjectByPageData();
      editDialogOverflowVisible.value = false;
      ElMessage({
        message: "修改成功",
        grouping: true,
        type: "success",
      });
    };
    const handleSelectionChange = (val) => {
      console.log(val);
      choseId.value = val.map((item) => item.id);
    };
    const getAlluserInfo = async () => {
      const res = await webRequest.people.getAllPeoleInfoMethod();
      allUserInfo.value = res.data.data;
      console.log(res);
    }
    // 批量删除
    const deleteMore = async () => {
      console.log(choseId.value);
      if (choseId.value == 0) {
        ElMessage({
          message: "请选择要删除的数据",
          grouping: true,
          type: "warning",
        });
        return;
      }
      const res = await webRequest.projectDetail.deleteProjectBatch({
        id: choseId.value,
      });
      console.log(res);
      getProjectByPageData();
      dialogVisible.value = false;
      ElMessage({
        message: "删除成功",
        grouping: true,
        type: "success",
      });
    };
    // 导入
    const exportTableMore = () => {
      uploadFileDialog.value = true;
    };
    const exportTable = () => {
      console.log("导入");
      uploadFileDialog.value = true;

    };
    const uploaFileMethod = async (e) => {
      console.log(e);
    };
    const handleChange = (file, fileList) => {
      console.log(file, fileList);
      file.value = file;
      filePath.value = file.raw;
    };
    // 导出
    const importTable = () => {
      console.log("导出");
    };
    const uploaFileError = (file) => {
      console.log(file);
    };
    const uploaFileSure = async () => {
      console.log(file.value, 'dsjkfhdskjhdskjfhsdjkhfkj');
      //通过FormData构造函数创建一个空对象
      const formdata = new FormData()
      formdata.append('file', filePath.value)
      try {
        let res = await webRequest.projectDetail.importProject(formdata);
        console.log(res, 'jkdshgfdskjhfdjkshfdsjkhf');
        if (res.data.code == 200) {
          if (res.data.data.duplicateProjects.length > 0) {
            ElMessage({
              message: "导入成功,有重复数据  " + res.data.data.duplicateProjects,
              grouping: true,
              type: "success",
            });
          } else {
            ElMessage({
              message: "导入成功",
              grouping: true,
              type: "success",
            });
          }
          // 成功后清除上传的文件
          console.log(upload);

          upload.value.clearFiles();
          uploadFileDialog.value = false;
          getProjectByPageData();
        } else {
          ElMessage({
            message: "导入失败",
            grouping: true,
            type: "error",
          });
        }
      } catch (error) {
        console.log(error, 'error');
        ElMessage({
          message: "导入失败",
          grouping: true,
          type: "error",
        });
      }
    };
    // 导出
    const exportProject = async () => {
      isExport.value = true;
    };
    // const exportSure = async () => {
    //   let res = await webRequest.projectDetail.exportProject();
    //   // 将数据从buffer转换为xlsx文件
    //   const blob = new Blob([res], {
    //     type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    //   });
    //   FileSaver.saveAs(blob, 'project_data.xlsx');
    //   // let res = await webRequest.projectDetail.exportProject();
    //   // console.log(JSON.stringify(res), "res");
    //   // // 将数据从buffer转换为xlsx文件
    //   // const blob = new Blob([res.data], {
    //   //   type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    //   // });
    //   // FileSaver.saveAs(blob, 'project_data.xlsx');
    // };
    const exportSure = async () => {
      try {
        // 假设 webRequest.projectDetail.exportProject() 返回一个包含 data 属性的对象
        const res = await webRequest.projectDetail.exportProject();

        // 检查返回的数据是否符合预期
        if (res && res.data) {
          // 使用 FileSaver 保存数据到文件
          const blob = new Blob([res.data], {
            type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
          });

          // 调用 saveAs 方法保存文件
          FileSaver.saveAs(blob, 'project_data.xlsx');
        } else {
          console.error("未找到要导出的数据");
        }
      } catch (error) {
        console.error("导出过程中出现错误:", error);
      }
    };

    getAlluserInfo()
    return {
      currentPage1,
      projectDetail,
      tableData,
      showProject,
      showDialogOverflowVisible,
      handleSizeChange,
      handleCurrentChange,
      handleDelete,
      showDeleteTip,
      dialogVisible,
      total,
      pageSize,
      handleEdit,
      editDialogOverflowVisible,
      editProject,
      statusArr,
      deleteMore,
      handleSelectionChange,
      uploadFileDialog,
      exportTableMore,
      uploaFileError,
      exportTable,
      importTable,
      uploaFileMethod,
      handleChange,
      uploaFileSure,
      exportProject,
      exportSure,
      isExport,
      getAlluserInfo,
      allUserInfo,
      dayjs,
      handleCheckChange,
      upload
    };
  },
};
</script>

<style lang="css" scoped>
.projectCenter {
  width: 95%;
  padding: 20px;
  margin: auto;
  background-color: white;
  position: relative;
  height: 95%;
}

.projectCenter_top {
  display: flex;
  justify-content: space-between;
}

.footer_page {
  position: absolute;
  bottom: 0;
  right: 0;
  margin: 20px;
}
</style>
